/*
 * Logger.cpp
 *
 *  Created on: 5/10/2014
 *      Author: gustavo
 */

#include <iostream>
#include <fstream>
#include <unistd.h>
#include "Logger.h"
#include <ConcurrencyFiles.h>

#include <stdio.h>

using namespace std;

Logger::Logger():isEnabled(false) {
}

Logger::~Logger() {
	if(isEnabled) {
		if (logFile.is_open()) {
			cout<<"Se abrio el log"<<endl;
		logFile.close();
		}
	}
	if (loggerInstance) {
		delete loggerInstance;
	}
}


Logger* Logger::loggerInstance = NULL;

Logger* Logger::getInstance() {
	 if ( loggerInstance == 0 ) {
		 loggerInstance = new Logger();
	 }
	 return loggerInstance;
}

void Logger::log(LoggerLevel tag, const string& msg) {

	static const char * LoggerLevelEnumValue[] = { "INFO", "WARNING", "ERROR" };

	if (this->isEnabled) {
		LockFile lock(ConcurrencyFiles::LOGPATH);
		lock.tomarLock();
		long int actualTime;
		time(&actualTime);
		logFile <<'[' << getpid() << ']' << LoggerLevelEnumValue[tag] <<" - "<< msg.c_str() <<" - "<< ctime(&actualTime) << endl;
		logFile.flush();
		lock.liberarLock();
	}
}

void Logger::enabled(bool enabled) {
	this->isEnabled = enabled;
	logFile.open (ConcurrencyFiles::LOGPATH.c_str(), ios::app | ios::out );
}
